package com.demo.my.shop.web.admin.web.controller;

import com.demo.my.shop.domain.TbUser;
import com.demo.my.shop.web.admin.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Autowired
    private TbUserService tbUserService;

    @RequestMapping(value = {"", "login"}, method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(@RequestParam(required = true) String email, @RequestParam(required = true) String password, HttpServletRequest request, Model model) {
        TbUser user = tbUserService.login(email, password);

        if (user == null) {
            model.addAttribute("message", "用户名或密码错误,请重新输入");
            return login();
        } else {
            //登录信息放入会话
            request.getSession().setAttribute("user", user);
            return "redirect:/main";
        }
    }
}